﻿using System;
using System.Web;
using System.IO;

public partial class OpenProjectToXML : System.Web.UI.Page
{
    Data.VarParams varParams;
    Data.DataConsolidation dc;
    Data.MyListString projectItems;
    Data.Data analysisProject;

    protected void Page_Load(object sender, EventArgs e)
    {
        try {
            Response.ContentType = "text/xml;charset=UTF-8";

            String myDataDir = (String)Session["MyApplicationDirectory"];
            if (myDataDir == null)
            {
                myDataDir = Request.Params["a"];
                if (myDataDir == null)
                    Response.Write(" Your session is expired or this page wasn't started correctly. Try starting it with ?a=windmill for our demo data.");
            }

            // this is to be a drive/subdir where variables.config and license.config reside
            String myApplicationDir = Request.PhysicalApplicationPath + myDataDir;
            String sessionId = Session.SessionID;
            String errMsg = InitData(myApplicationDir, sessionId);
            if (errMsg != null)
            {
                Response.Write(errMsg);
            }
            else
            {
               
                Response.Write( "<?xml version='1.0' encoding='Windows-1252'?>" );

                String xslFile;
                xslFile =  (String) Request[ "xslFile" ];
                if (xslFile != null)
                {
                    if (System.IO.File.Exists(Request.PhysicalApplicationPath + "\\" + xslFile))
                    {
                        String buf = "<?xml-stylesheet type='text/xsl' href='/DotNetOpenSource/" + xslFile + "' ?>";
                        Response.Write(buf);
                    }
                }
                
                Response.Write( "<Projects>" );
                
                String fileName = (String) Request[ "uploadedProjectFile" ];
                if( fileName != null )
                {
                    try
                    {
                        string[] temp = System.IO.File.ReadAllLines(fileName);
                        Data.MyListString lines = new Data.MyListString( temp );
                        RunScriptCommandsToXML( Response, lines );
                    } catch( Exception ){}                             
                }
                else
                {
                    RunAllProjectFilesToXML( Response );
                }

                Response.Write( "</Projects>" );
            }

        } catch( Exception )
        {
        }
    }
    
    public void RunAllProjectFilesToXML( HttpResponse response )
    {
        Data.MyListString filelist = Data.MyDirectory.GetFiles(varParams.GetMyProjectsDir());

        for( int projectIndex = 0,  projectCount = filelist.GetCount() ;
                projectIndex < projectCount ; projectIndex++ )
        {
            String projectFileName = filelist.Get( projectIndex );
            if( projectFileName.StartsWith( "_" ) == false )
            {
                RunProjectFileToXML( response, projectFileName );
            }
        }
    }

    private void RunProjectFileToXML( HttpResponse response, String projectFileName )
    {
        String error = LoadProjectFromProjectFile( projectFileName );
        if( error != null )
            response.Write( "There was a problem building this project. " + error );
        
        else
        {
            error = ExecuteProjectLines();
            if( error != null )
                response.Write( error );
            else
                OutputXml.RunExecutedProjectToXml( response, projectFileName, analysisProject );
        }
    }

    private void RunScriptCommandsToXML( HttpResponse response, Data.MyListString projectItems )
    {
        String error = ExecuteProjectLines();
        if( error != null )
            response.Write( error );
        else
            OutputXml.RunExecutedProjectToXml( response, null, analysisProject );
    }
    
    public String LoadProjectFromProjectFile( String projectFileName )
    {
        if( projectFileName == null || projectFileName.Length == 0 )
        {
            return "Invalid project filename";
        }
        
        String fullProjectFileName = varParams.GetMyProjectsDir() + projectFileName;
        if( Data.MyFile.Exists( fullProjectFileName ) == false )
        {
            return fullProjectFileName + " not found";
        } 
        
        projectItems = Data.MyFile.ReadAllLines( varParams, fullProjectFileName );
        if( projectItems == null || projectItems.GetCount() == 0 )
            return "problem with contents of " + fullProjectFileName;
        else
            return null;
    }

    private String ExecuteProjectLines()
    {
        analysisProject = new Data.Data();
        if( analysisProject == null )
            return "Failed to load, probably low memory or corrupted files" ;

        for( int i=0, count = projectItems.GetCount() ; i < count ; i++ )
        {
            String scriptItem = projectItems.Get( i );
            String message = ExecuteLine( scriptItem ) ;
            if( message != null )
                return "Line " + i.ToString() + message ;
        }
        return null;    // a return value of null means success 
    }
    
    private String ExecuteLine( String scriptItem )
    {
        Boolean success = dc.RunScript( scriptItem, analysisProject, true );
        if( success == false )
            return " failed: " + scriptItem;
        else
            return null;
    }

    public String InitData( String variablesPath, String sessionId )
    {
        varParams = new Data.VarParams();
        if( varParams == null )
            return "Failed to load, probably low memory or corrupted files" ;

        String errMsg = varParams.ReadFile( variablesPath, sessionId );
        if( errMsg != null )
            return errMsg;

        dc = new Data.DataConsolidation( varParams );

        return null;
    }
}
